package com.study.happystudy.tool;

import java.util.Random;
import java.util.concurrent.atomic.AtomicLong;

public class UniqueIdGenerator {
    private static final AtomicLong timestamp = new AtomicLong(System.currentTimeMillis() % 10_000_000);
    private static final Random random = new Random();

    public static String generateUniqueId() {
        long currentTimestamp = System.currentTimeMillis() % 10_000_000;
        // 如果当前时间小于等于上次的时间戳，则等待直到时间戳增加，以避免重复。
        while (currentTimestamp <= timestamp.get()) {
            currentTimestamp = System.currentTimeMillis() % 10_000_000;
        }
        // 更新时间戳
        timestamp.set(currentTimestamp);

        // 生成随机数，确保ID的唯一性
        int randomNum = random.nextInt(1000);

        // 格式化时间戳和随机数，生成ID
        return String.format("%07d%03d", currentTimestamp, randomNum);
    }

}
